package com.yc.testupload.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.Cookie;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "logoutServlet", value = "/logout")
public class LogoutServlet extends HttpServlet {

    private static final Logger logger = LogManager.getLogger(LogoutServlet.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();

        try {
            // 获取当前会话
            HttpSession session = request.getSession(false);
            if (session != null) {
                // 获取用户名用于日志记录
                String username = (String) session.getAttribute("username");

                // 使会话失效
                session.invalidate();

                logger.info("用户 {} 退出登录成功", username);
            }
            
            // 清除登录相关Cookie
            clearLoginCookies(request, response);
            logger.debug("已清除登录相关Cookie");

            // 无论是否存在会话，都返回成功
            out.write("{\"code\":0,\"message\":\"退出登录成功\"}");
        } catch (Exception e) {
            logger.error("退出登录过程中发生错误: {}", e.getMessage(), e);
            out.write("{\"code\":500,\"message\":\"系统错误，请稍后重试\"}");
        } finally {
            out.flush();
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 对于GET请求，直接调用POST处理
        doPost(request, response);
    }
    
    // 从请求中提取域名，用于设置Cookie的Domain属性
    private String getDomainFromRequest(HttpServletRequest request) {
        String serverName = request.getServerName();
        // 如果是localhost或IP地址，不设置Domain属性
        if (serverName.equals("localhost") || serverName.matches("\\d+\\.\\d+\\.\\d+\\.\\d+")) {
            return null;
        }
        // 对于生产环境域名，提取主域名（如从example.com.cn提取.com.cn）
        // 简单实现：保留最后两级域名
        int lastDotIndex = serverName.lastIndexOf('.');
        if (lastDotIndex > 0) {
            int secondLastDotIndex = serverName.lastIndexOf('.', lastDotIndex - 1);
            if (secondLastDotIndex > 0) {
                // 包含多个点，返回最后两级
                return serverName.substring(secondLastDotIndex + 1);
            }
        }
        return serverName;
    }
    
    // 清除登录相关Cookie
    private void clearLoginCookies(HttpServletRequest request, HttpServletResponse response) {
        logger.info("开始清除登录相关Cookie");
        
        // 获取当前域名
        String domain = getDomainFromRequest(request);
        
        // 清除username Cookie
        String usernameCookieStr = String.format("username=; Max-Age=0; Path=/; HttpOnly=true; SameSite=Lax; Secure=false%s", 
                domain != null ? "; Domain=" + domain : "");
        response.addHeader("Set-Cookie", usernameCookieStr);
        logger.info("已清除username Cookie");
        
        // 清除userId Cookie
        String userIdCookieStr = String.format("userId=; Max-Age=0; Path=/; HttpOnly=true; SameSite=Lax; Secure=false%s", 
                domain != null ? "; Domain=" + domain : "");
        response.addHeader("Set-Cookie", userIdCookieStr);
        logger.info("已清除userId Cookie");
        
        // 清除persistent_login Cookie
        String persistentCookieStr = String.format("persistent_login=; Max-Age=0; Path=/; HttpOnly=true; SameSite=Lax; Secure=false%s", 
                domain != null ? "; Domain=" + domain : "");
        response.addHeader("Set-Cookie", persistentCookieStr);
        logger.info("已清除persistent_login Cookie");
        
        // 清除JSESSIONID Cookie
        String jsessionIdCookieStr = String.format("JSESSIONID=; Max-Age=0; Path=/; HttpOnly=true; SameSite=Lax; Secure=false%s", 
                domain != null ? "; Domain=" + domain : "");
        response.addHeader("Set-Cookie", jsessionIdCookieStr);
        logger.info("已清除JSESSIONID Cookie");
        
        logger.info("已清除所有登录相关Cookie");
    }
}